package controller

import (
	"CampusCloudAid/logic"
	"CampusCloudAid/models"
	"CampusCloudAid/pkg/printfile"
	"fmt"
	"github.com/gin-gonic/gin"
	"net/http"
)

func Check(ctx *gin.Context) {
	var requestBody models.RequestBody

	// 绑定并解析请求体
	if err := ctx.ShouldBindJSON(&requestBody); err != nil {
		ctx.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request body"})
		return
	}

	// 逐个打印列表中的元素
	for _, item := range requestBody.List {
		encode := item
		fmt.Println("Item:", item)
		outputFile := "./storage/parse_data/" + encode + "_output.txt"
		// 调用重定向函数
		restore, err := printfile.RedirectOutputToFile(outputFile)
		if err != nil {
			fmt.Println("Failed to redirect output:", err)
			return
		}
		defer restore() // 确保在程序结束时恢复输出
		fmt.Println("开始测试: ", encode)
		//redis数据
		allResults, err := logic.GetKeys(encode)
		if err != nil {
			ResponseError(ctx, CodeRedisError)
			return
		}
		//在线领域文档映射
		topicList, err := logic.GetTopicList()
		if err != nil {
			ResponseError(ctx, CodeOnlineTopicError)
			return
		}
		//在线类型文档映射
		typeList, err := logic.GetTypeList()
		if err != nil {
			ResponseError(ctx, CodeOnlineTypeError)
			return
		}
		_, err = logic.Check(encode, allResults, topicList, typeList)
		if err != nil {
			ResponseErrorWithMsg(ctx, CodeFalse, err)
			return
		}
		fmt.Println("如果一以上都没有出现报错信息的话，那么!")
		fmt.Println(encode + "恭喜你，领域、类型、时间、标题经过检查没有问题!!!")
	}

	//传入参数
	//encode := ctx.Query("encode")

	ResponseSuccess(ctx, true)
	return
}
